<template>
  <t-button
    v-permission="['system:order-designer:enter-designer-page']"
    theme="primary"
    @click="handleOpenDialog"
  >
    转设计数据
  </t-button>
  <!-- 对话框 -->
  <t-dialog
    v-model:visible="visible"
    attach="body"
    width="70%"
    :confirmBtn="null"
    destroy-on-close
    header="转设计数据"
    @closed="handleClosed"
  >

    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }"
      :default-params="defaultSearchParams" @submit="handleSeachTable">
      <t-col :span="3">
        <t-form-item label="客服" name="saleId">
          <t-cascader
            v-model:value="params.saleId"
            :options="saleTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
 
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="设计师" name="userId">
          <t-cascader
            v-model:value="params.userId"
            :options="designerTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
 
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="来源渠道" name="channelSource">
          <t-select
            v-model:value="params.channelSource"
            :options="channelList"
            :keys="{ value: 'id', label: 'name' }"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="设计阶段" name="stage">
          <t-select
            v-model:value="params.stage"
            :options="dictionaryStore.get('order_designer_stage')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="是否公海" name="inGh">
          <t-select
            v-model:value="params.inGh"
            :options="[
              { label: '是', value: '1' },
              { label: '否', value: '0' },
            ]"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="是否废单" name="deleted">
          <t-select
            v-model:value="params.deleted"
            :options="[
              { label: '是', value: '1' },
              { label: '否', value: '0' },
            ]"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="转设计时间" name="cjsj">
          <t-date-range-picker
            allow-input
            v-model:value="params.cjsj"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
            @change="
              (value) => {
                const [beginTime, endTime] = value;
                params.beginTime = beginTime;
                params.endTime = endTime;
              }
            "
          />
        </t-form-item>
      </t-col>
    </custom-search>
     <!-- 自定义表格 -->
     <custom-table ref="customTableRef" row-key="id" :columns="columns" :api="getOrderDesignerData"
      column-controller-key="ProjectEngineeringList">
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-radio-group v-model="defaultCompany" theme="button" @change="handleCompanyChange">
            <t-radio-button :value="_.id" v-for="_ in companyList">{{ _.name }}</t-radio-button>
          </t-radio-group>
        </div>
      </template>

      
      
      <template #saleId="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #designerId="{ row }">
        {{ userStore.getUserNameById(row.userId) }}
      </template>
      <template #stage="{ row }">
        {{ dictionaryStore.analysis('order_designer_stage', row.stage) }}
      </template>
      <template #inGh="{ row }">
        {{ dictionaryStore.analysis('is_type', row.inGh) }}
      </template>
      <template #deleted="{ row }">
        {{ dictionaryStore.analysis('is_type', row.deleted) }}
      </template>
      
      <template #channelSource="{ row }">
        {{ channelList.find((item) => item.id.toString() === row.channelSource)?.name }}
      </template>
      
      <template #propertyName="{ row }">
        {{propertyInfoList.find((item) => item.id === row.propertyName)?.name}}
        <span style="color: gray;">{{ row.address }}</span>
      </template>
      <template #createTime="{ row }">
        {{ row.createTime?dayjs(row.createTime).format('YYYY-MM-DD'):'' }}
      </template>
     
    </custom-table>
  </t-dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, nextTick, PropType, Ref, ref, useTemplateRef } from 'vue';

import {
  transformDesignExtension,
} from '@/api/approve/approve';
import { getUserListByCompanyIdAndRoleId, getUserListByRoleCode } from '@/api/system/user';
import { getOrderDesignerData } from '@/api/order/design';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import listToTree from '@/utils/listToTree';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import { propertyManageCRUD } from '@/api/config/property';
import { channelManageCRUD } from '@/api/config/common-config';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 公司列表
const companyList = ref([]);
// 默认公司
const defaultCompany = ref()
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = [{ id: null, name: '全部公司' }, ...data];
      defaultCompany.value = null
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetCompanyList();
// 公司切换
const handleCompanyChange = () => {
  handleInitTable();
};
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 渠道列表
const channelList = ref([]);
// 处理获取渠道列表
const handleGetChannelList = () => {
  const params = {
    pageSize: -1,
  };
  channelManageCRUD
    .page(params)
    .then((data) => {
      channelList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetChannelList();

const visible = ref(false)
// emits
const emits = defineEmits(['requestSuccess']);
// columns
const columns: TableCol[] = [
  { colKey: 'stage', title: '设计阶段', width: 80, fixed: 'left' },
  { colKey: 'name', title: '客户名称', width: 80, fixed: 'left' },
  { colKey: 'propertyName', title: '楼盘地址', fixed: 'left', width: 180 },
  { colKey: 'phone', title: '手机号码', width: 110 },
  { colKey: 'saleId', title: '客服', width: 80 },
  { colKey: 'designerId', title: '设计师', width:80 },
  { colKey: 'channelSource', title: '来源渠道', width: 130 },
  { colKey: 'inGh', title: '是否公海', width: 80 },
  { colKey: 'deleted', title: '是否废单', width: 80 },
  { colKey: 'createTime', title: '转设计时间', width: 130 },

];
const getCurrentMonthRange = () => {
      const now = new Date();
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      
      
      return [dayjs(firstDay).format('YYYY-MM-DD 00:00:00'), dayjs(lastDay).format('YYYY-MM-DD 23:59:59')];
    };
// 处理打开对话框
const handleOpenDialog = async () => {
  visible.value = true
  console.log(customSearchRef.value,'customSearchRef');
  await nextTick();
  handleInitTable();

  
};
// 处理关闭对话框
const handleClosed = () => {
  visible.value = false
}
// 精简部门列表
const simpleDeptList = ref([]);
// 精简部门树
const simpleDeptTree = ref([]);
// 处理获取精简部门
const handleGetSimpleDeptTree = () => {
  getSimpleDeptList().then((data) => {
    simpleDeptList.value = data;
    simpleDeptTree.value = listToTree(data);
  });
};
handleGetSimpleDeptTree();
// 客服列表
const saleList = ref([]);
// 设计师列表
const designerList = ref([]);

// 获取用户通过rolecode
const fetchUsersByRole = async (roleCode: string, targetList: Ref<any[], any[]>) => {
  try {
    const data = await getUserListByRoleCode({ roleCode });
    data.forEach((item:any) => {
      item.name = item.nickname
      item.parentId = item.deptId
    });
    targetList.value = data;
  } catch (error) {
    console.error(`Error fetching users with role ${roleCode}:`, error);
    targetList.value = []; // Reset on error
  }
};
// 初始化所有用户
const initializeUserLists = () => {
  fetchUsersByRole('designer', designerList);
  fetchUsersByRole('sloe', saleList);
};

// Call initialization
initializeUserLists();
// 3. 合并部门和用户数据，生成树形结构
const generateCombinedTree = (deptTree: any[], userList: any[], userType: string) => {
  // 创建用户按部门ID分组的映射
  const userMap = new Map<number, any[]>();
  userList.forEach(user => {
    if (!userMap.has(user.deptId)) {
      userMap.set(user.deptId, []);
    }
    userMap.get(user.deptId).push({
      ...user,
      isUser: true,
      userType: userType
    });
  });

  // 递归处理部门树
  const processTree = (nodes: any[]): any[] => {
    return nodes.map(node => {
      const newNode = { ...node };
      
      // 处理子部门
      if (newNode.children) {
        newNode.children = processTree(newNode.children);
      } else {
        newNode.children = [];
      }
      
      // 添加当前部门的用户
      if (userMap.has(newNode.id)) {
        newNode.children.push(...userMap.get(newNode.id));
      }
      
      // 保留有用户或有子部门的节点
      if (newNode.children.length > 0) {
        return newNode;
      }
      
      return null;
    }).filter(Boolean);
  };

  return processTree(deptTree);
};
const designerTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, designerList.value, 'designer');
});
const saleTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, saleList.value, 'sloe');
});
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
const handleSeachTable=(params:any) =>{
  if(params=='reset') {
    customSearchRef.value.params.endTime = ''
    customSearchRef.value.params.beginTime = ''
  }

  handleInitTable()
  
}
// 默认搜索参数
const defaultSearchParams = computed(() => {
  const [start, end] = getCurrentMonthRange();
  return {
    cjsj: [start, end],
    beginTime: start,
    endTime: end
  };
});
// 处理初始化表格
const handleInitTable = () => {
  
  
  const params = { ...customSearchRef.value.params, companyId: defaultCompany.value, };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};
</script>
<style lang="less" scoped>
:deep(.t-radio-group .t-radio-button) {
  border: none;
  border-radius: 18px !important;
  margin-left: 11px;
}
:deep(.t-radio-group .t-radio-button.t-is-checked) {
  background-color: #f2f3f5;
}
</style>
